package com.glory.brepda.activity.mfg;

/**
 * 批次解绑料盒
 */

import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.brepda.R;
import com.glory.brepda.adapter.LotCarrierUnBindAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

// 批次解绑载具逻辑
public class LotUnBindActivity extends BaseActivity {


    @BindView(R.id.tvTitle)
    TextView tvTitle;

    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;

    @BindView(R.id.etLotID)
    FreeUI_ClearEditText etLotID;

    // 工序
    @BindView(R.id.tvStepName)
    TextView tvStepName;

    // 批次数量
    @BindView(R.id.tvMainQty)
    TextView tvMainQty;

    @BindView(R.id.llMain)
    LinearLayout llMain;

    // 料盒解绑原因下拉选择框
    // fl(FrameLayout)、tv(TextView)、iv(ImageView)
    @BindView(R.id.flCarrierUnBindReason)
    FrameLayout flCarrierUnBindReason;
    @BindView(R.id.tvCarrierUnBindReason)
    TextView tvCarrierUnBindReason;
    @BindView(R.id.ivCarrierUnBindReason)
    ImageView ivCarrierUnBindReason;

    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;

    @BindView(R.id.rvUnBindLotList)
    RecyclerView rvUnBindLotList;

    @BindView(R.id.etBingLotID)
    FreeUI_ClearEditText etBindLotID;

    @BindView(R.id.etUnBingLotID)
    FreeUI_ClearEditText etUnBindLotID;

    // 绑定载具类别下拉选择框
    // fl(FrameLayout)、tv(TextView)、iv(ImageView)
    FrameLayout flCarrierType;
    TextView tvCarrierType;
    ImageView ivCarrierType;

    // 料盒类别下拉框配置
    private FreeUI_GeneralPop carrierTypePop;
    private final ArrayList<String> carrierBindTypeList = new ArrayList<>(Arrays.asList("料盒","黑箱"));

    // 料盒解绑原因下拉框配置
    private FreeUI_GeneralPop carrierUnBindReasonPop;
    private ArrayList<String> carrierUnBindReasonList = new ArrayList<>(Arrays.asList("料盒绑错","料盒变形"));

    // 批次已绑定料盒列表
    private LotCarrierUnBindAdapter mLotBindAdapter;
    // 批次已选择解绑料盒列表
    private LotCarrierUnBindAdapter mLotUnBindAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_lot_unbind;
    }

    @Override
    protected void initView() {
        initLayout();

        initAllRecyclerView();

        // 初始化料盒解绑原因，直接给其设置一个值就好
        tvCarrierUnBindReason.setText(carrierUnBindReasonList.get(0));

        // 编辑需要解绑的料盒号时，把值从当前列表转移到删除列表中
        initEdit(etBindLotID, this::onEtBindLotIDTextChangeListener);

        // 编辑需要取消解绑的料盒号时，把值从当前列表还原到绑定列表中
        initEdit(etUnBindLotID, this::onEtUnBindLotIDTextChangeListener);

        // 注册编辑批次号框触发的事件
        initEdit(etLotID, this::onEtLotIDTextChangeListener);
    }

    private void initLayout() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);


        // 初始化载具类别下拉框
        flCarrierType = findViewById(R.id.flCarrierType);
        tvCarrierType = findViewById(R.id.tvCarrierType);
        ivCarrierType = findViewById(R.id.ivCarrierType);
        // 载具类别下拉框设定初始值：料盒
        tvCarrierType.setText(carrierBindTypeList.get(0));
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit, R.id.flCarrierUnBindReason, R.id.flCarrierType})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvBaseSubmit) {
            if (mLotUnBindAdapter.getData().size() <= 0 || StringUtils.isEmpty(etLotID.getText())) {
                showToast("解绑载具不能为空", false);
                return;
            }

            if (StringUtils.isEmpty(tvCarrierUnBindReason.getText())) {
                showToast("必须填写解绑原因", false);
                return;
            }
            // 提交时弹出确认取消框
            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要提交?", new FreeUI_CommonCallback() {
                @Override
                public void onSuccess() {
                    // 用户点击了确认，执行解绑料盒动作
                    FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                            (new TypeToken<BaseResponseBean<JSONObject>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(LotUnBindActivity.this,false,getSupportFragmentManager())){
                                showToast("批次解绑成功", true);
                                // 清空解绑载具列表
                                clearDataInAdapter(mLotUnBindAdapter);
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<JSONObject>> response) {
                            super.onError(response);
                            loadError(response.getException(), "LOTREASSIGNMULTICARRIER");
                        }
                    };
                    JsonObject map = new JsonObject();
                    map.addProperty("ACTIONTYPE", "unBind");
                    map.addProperty("LOTID", String.valueOf(etLotID.getText()));
                    List<String> lotList = new ArrayList<>(mLotUnBindAdapter.getData());
                    map.add("DURABLEIDLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传载具集合
                    // 传料盒解绑原因
                    map.addProperty("CARRIERACTIONCOMMENT", String.valueOf(tvCarrierUnBindReason.getText()));
                    NetUtils.requestPostNet("IF.LOTVEHICLEBINDING", "Common", LotUnBindActivity.this, map, callBack);
                } // end success callback
            }, ()->{}).show(getSupportFragmentManager(),"LOTVEHICLEBINDING");
        } else if (view.getId() == R.id.flCarrierUnBindReason) {
            // 下拉选择框选择
            carrierUnBindReasonPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCarrierUnBindReason.getWidth(), carrierUnBindReasonList, ivCarrierUnBindReason, (codeS, i) -> {
                tvCarrierUnBindReason.setText(codeS);
            });
            FreeApi_PopUtils.setArrowShow(ivCarrierUnBindReason);
            carrierUnBindReasonPop.showAsDropDown(flCarrierUnBindReason, 0, 0);

        } else if (view.getId() == R.id.flCarrierType) {
            // 料盒类别下拉选择框选择
            carrierTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flCarrierType.getWidth(), carrierBindTypeList, ivCarrierType, (codeS, i) -> {
                tvCarrierType.setText(codeS);
            });
            FreeApi_PopUtils.setArrowShow(ivCarrierType);
            carrierTypePop.showAsDropDown(flCarrierType, 0, 0);
        }
    }

    private void initAllRecyclerView() {
        //rvUnBindLotList
        initRecyclerView(rvUnBindLotList, this);
        mLotUnBindAdapter = new LotCarrierUnBindAdapter(null);
        mLotUnBindAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mLotUnBindAdapter.isFirstOnly(true);
        mLotUnBindAdapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            // 触发了点击事件，这里需要移除掉数据，然后还原到绑定框里面
            Object item = baseQuickAdapter.getItem(i);
            baseQuickAdapter.remove(i);
            mLotBindAdapter.addData(String.valueOf(item));
        });
        rvUnBindLotList.setAdapter(mLotUnBindAdapter);

        initRecyclerView(rvLotList, this);
        mLotBindAdapter = new LotCarrierUnBindAdapter(null);
        mLotBindAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mLotBindAdapter.isFirstOnly(true);
        mLotBindAdapter.setOnItemClickListener((baseQuickAdapter, view, i) -> {
            // 触发了点击事件，这里需要移除掉数据，然后添加到删除框里面
            Object item = baseQuickAdapter.getItem(i);
            baseQuickAdapter.remove(i);
            mLotUnBindAdapter.addData(String.valueOf(item));
        });
        rvLotList.setAdapter(mLotBindAdapter);
    }

    /**
     * 编辑需要解绑的料盒号时，把值从当前列表转移到删除列表中
     * @param carrierId 载具号
     */
    private void onEtBindLotIDTextChangeListener(String carrierId) {
        // 检查用户是否有输入批次查询批次绑定的载具
        if (StringUtils.isEmpty(etLotID.getText())) {
            showToast("请先扫描批次查询载具", false);
            return;
        }

        // 检查批次是否有绑定载具
        List<String> carrierList = mLotBindAdapter.getData();
        if (carrierList.size() <= 0) {
            showToast("批次没有绑定载具", false);
        }

        // 检索验证扫入的值是否在绑定列表中
        int index = mLotBindAdapter.getData().indexOf(carrierId);
        if (index < 0) {
            showToast("批次没有绑定该载具：" + carrierId, false);
            return;
        }
        // 绑定列表移除载具
        mLotBindAdapter.remove(index);
        // 删除列表添加载具
        mLotUnBindAdapter.addData(carrierId);
        MyUtils.clearTextInTextView(etBindLotID);
        new Handler().postDelayed(() -> etBindLotID.requestFocus(), 500);
    }

    /**
     * 输入批次号是，根据批次号查询批次绑定的料盒
     * @param lotId 批次号
     */
    private void onEtLotIDTextChangeListener(String lotId) {
        //获取批次绑定的料盒信息
        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    // 获取服务器传过来料盒数据
                    LotInfoEntity.LotBean lot = response.body().getResponse().getBody().getLOT();
                    List<String> lotCarrierList = response.body().getResponse().getBody().getDURABLELIST();
                    if (lotCarrierList != null && lotCarrierList.size() > 0) {
                        new Handler().post(() -> {
                            // 更新视图
                            // 这里直接使用addData会报错，参考代码后先获取视图的数据列表，修改数据列表的值
                            mLotBindAdapter.getData().clear();
                            mLotBindAdapter.getData().addAll(lotCarrierList);
                            mLotBindAdapter.notifyDataSetChanged();
                        });
                        // 更新 工步和批次数量的数据
                        tvStepName.setText(lot.getSTEPDESC());
                        tvMainQty.setText(lot.getMAINQTY());

                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"LOTVEHICLEBINDING");
                // 请求失败的话需要及时清理两个列表中的数据
                MyUtils.clearTextInTextView(tvStepName, tvMainQty);
                clearDataInAdapter(mLotBindAdapter);
                clearDataInAdapter(mLotUnBindAdapter);
            }
        };
        // 发起请求前先清空数据
        // 1、工序、数量
        MyUtils.clearTextInTextView(tvStepName, tvMainQty);
        // 2、校验和取消校验的残余数据
        clearDataInAdapter(mLotBindAdapter);
        clearDataInAdapter(mLotUnBindAdapter);

        // 发起请求
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","query");
        map.addProperty("LOTID",lotId);
        map.addProperty("CARRIERTYPE", String.valueOf(tvCarrierType.getText()));
        NetUtils.requestPostNet("IF.LOTVEHICLEBINDING","Common", LotUnBindActivity.this,map,callBack);
    }

    /**
     * 编辑需要取消解绑的料盒号时，把值从当前列表还原到绑定列表中
     * @param carrierId 料盒号
     */
    private void onEtUnBindLotIDTextChangeListener(String carrierId) {
        //

        // 检索验证扫入的值是否在绑定列表中
        int index = mLotUnBindAdapter.getData().indexOf(carrierId);
        if (index < 0) {
            showToast("解绑载具列表中不存在该载具：：" + carrierId, false);
            return;
        }
        // 绑定列表移除载具
        mLotUnBindAdapter.remove(index);
        // 删除列表添加载具
        mLotUnBindAdapter.addData(carrierId);
        MyUtils.clearTextInTextView(etUnBindLotID);
        new Handler().postDelayed(() -> etUnBindLotID.requestFocus(), 500);
    }

    /**
     * 清空适配器里面的数据
     * @param adapter RecycleView 适配器
     */
    private void clearDataInAdapter(BaseQuickAdapter<String, BaseViewHolder> adapter) {
        if (adapter.getData().size() > 0) {
            adapter.getData().clear();
            adapter.notifyDataSetChanged();
        }
    }
}
